package com.hotelManager.www.service;

import com.hotelManager.www.dao.ShopDao;
import com.hotelManager.www.dao.UserDao;
import com.hotelManager.www.dao.OrderDao;
import com.hotelManager.www.dao.RoomTypeDao;
import com.hotelManager.www.po.Shop;
import com.hotelManager.www.po.User;
import com.hotelManager.www.po.RoomType;
import com.hotelManager.www.util.JDBCUtils;
import java.sql.Connection;
import java.sql.SQLException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Date;

public class ShopService implements ShopServiceInterface {
    private static ShopDao shopDao;
    private final OrderDao orderDao;
    private final RoomTypeDao roomTypeDao = new RoomTypeDao();
    private final OrderService orderService = new OrderService();

    static {
        try {
            shopDao = new ShopDao();
        } catch (Exception e) {
            throw new RuntimeException("初始化ShopDao失败", e);
        }
    }

    public ShopService() {
        this.orderDao = new OrderDao();
    }

    @Override
    public Connection getConnection() {
        try {
            return JDBCUtils.getConnection();
        } catch (Exception e) {
            throw new RuntimeException("获取数据库连接失败", e);
        }
    }

    @Override
    public boolean create(Shop shop) {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.Shopregister(shop, conn);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public boolean update(Shop shop) {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.update(conn, shop);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public boolean delete(Integer id) {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.delete(conn, id);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public Shop findById(Integer id) {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.findById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public List<Shop> findAll() {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.findAll(conn);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public boolean registerShop(Shop shop, User user) {
        Connection conn = null;
        try {
            conn = getConnection();
            conn.setAutoCommit(false);

            UserDao userDao = new UserDao();

            // 检查用户是否已存在
            User existingUser = userDao.getUserByUsername(conn, user.getUsername());
            if (existingUser == null) {
                // 用户不存在，先注册用户
                if (!userDao.register(user, conn)) {
                    conn.rollback();
                    return false;
                }
                // 获取新注册用户的ID
                existingUser = userDao.getUserByUsername(conn, user.getUsername());
                if (existingUser == null) {
                    conn.rollback();
                    return false;
                }
            }

            // 设置店铺的user_id
            shop.setUserId(existingUser.getId());

            // 设置默认值
            shop.setAuditStatus("pending");
            shop.setSalesVolume(0);
            shop.setPublishTime(new Date());
            shop.setRevenue(BigDecimal.ZERO);

            // 注册店铺
            if (!shopDao.Shopregister(shop, conn)) {
                conn.rollback();
                return false;
            }

            conn.commit();
            return true;
        } catch (SQLException e) {
            try {
                if (conn != null) {
                    conn.rollback();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
            return false;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public List<Shop> getAllApprovedShops() {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.findByAuditStatus(conn, "approved");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public List<Shop> getShopsBySalesVolume() {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.findAllOrderBySalesVolume(conn);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public List<Shop> getShopsByTime() {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.findAllOrderByPublishTime(conn);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public List<Shop> searchShops(String keyword) {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.findByKeyword(conn, keyword);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 分页模糊查询店铺
    public List<Shop> searchShopsWithPagination(String keyword, int page, int pageSize) {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.findByKeywordWithPagination(conn, keyword, page, pageSize);
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public boolean updateShopSales(Integer shopId, Integer count) {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.updateSalesVolume(shopId, count);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public boolean updateShopStatus(Integer shopId, String status) {
        Connection conn = null;
        try {
            conn = getConnection();
            Shop shop = shopDao.findById(shopId);
            if (shop == null) {
                return false;
            }
            shop.setStatus(status);
            return shopDao.update(conn, shop);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public List<Shop> getPendingShops() {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.findByAuditStatus(conn, "pending");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public boolean updateShopAuditStatus(Integer shopId, String auditStatus) {
        Connection conn = null;
        try {
            conn = getConnection();
            Shop shop = shopDao.findById(shopId);
            if (shop == null) {
                return false;
            }
            shop.setAuditStatus(auditStatus);
            return shopDao.update(conn, shop);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public Shop getShopByUsername(String username) {
        Connection conn = null;
        try {
            conn = getConnection();
            UserDao userDao = new UserDao();
            User user = userDao.getUserByUsername(conn, username);
            if (user == null) {
                System.out.println("未找到用户：" + username);
                return null;
            }
            System.out.println("找到用户：" + username + "，ID：" + user.getId());
            
            // 使用用户ID查找对应的店铺
            Shop shop = shopDao.findByUserId(user.getId());
            if (shop == null) {
                System.out.println("未找到与用户ID " + user.getId() + " 关联的店铺");
            } else {
                System.out.println("找到店铺：" + shop.getShopname() + "，ID：" + shop.getId());
            }
            return shop;
        } catch (SQLException e) {
            System.out.println("数据库操作异常：" + e.getMessage());
            e.printStackTrace();
            return null;
        } catch (Exception e) {
            System.out.println("其他异常：" + e.getMessage());
            throw new RuntimeException(e);
        } finally {
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public Shop getShopByUserId(Integer userId) {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.findByUserId(userId);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 添加收藏
    public boolean addFavoriteShop(int userId, int shopId) {
        try {
            return shopDao.addFavorite(userId, shopId);
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 获取用户收藏的店铺
    public List<Shop> getFavoritesByUserId(int userId) {
        try {
            return shopDao.getFavoritesByUserId(userId);
        } catch (SQLException e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    // 取消收藏
    public boolean removeFavoriteShop(int userId, int shopId) {
        try {
            if (shopDao.removeFavorite(userId, shopId)) {
                return shopDao.updateFavoritesVolume(shopId, -1);
            }
            return false;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
    //通过收藏量来查看shop
    public List<Shop> getShopsByFavoritesVolume() {
        // Mock implementation: Replace with actual logic to fetch shops by favorites volume
        return new ArrayList<>();
    }

    // 更新店铺浏览量
    public boolean updateViewCount(Integer shopId) {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.updateViewCount(shopId);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 获取店铺房型列表
    public List<RoomType> getShopRoomTypes(Integer shopId) {
        Connection conn = null;
        try {
            conn = getConnection();
            return roomTypeDao.findByShopId(conn, shopId);
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 获取店铺销量统计
     * @param shopId 店铺ID
     * @return 包含不同时间维度销量数据的Map
     */
    public Map<String, Object> getSalesStatistics(int shopId) throws Exception {
        try (Connection conn = JDBCUtils.getConnection()) {
            // 获取店铺基本信息
            Shop shop = shopDao.findById(shopId);
            if (shop == null) {
                throw new IllegalArgumentException("店铺不存在");
            }

            // 获取今日销量
            LocalDateTime startOfDay = LocalDate.now().atStartOfDay();
            LocalDateTime endOfDay = LocalDate.now().plusDays(1).atStartOfDay();
            int todaySales = orderDao.countCompletedOrders(conn, shopId, startOfDay, endOfDay);
            
            // 获取本周销量
            LocalDateTime startOfWeek = LocalDate.now().minusDays(LocalDate.now().getDayOfWeek().getValue() - 1).atStartOfDay();
            LocalDateTime endOfWeek = startOfWeek.plusDays(7);
            int weekSales = orderDao.countCompletedOrders(conn, shopId, startOfWeek, endOfWeek);
            
            // 获取本月销量
            LocalDateTime startOfMonth = LocalDate.now().withDayOfMonth(1).atStartOfDay();
            LocalDateTime endOfMonth = startOfMonth.plusMonths(1);
            int monthSales = orderDao.countCompletedOrders(conn, shopId, startOfMonth, endOfMonth);
            
            // 获取总销量
            int totalSales = shop.getSalesVolume();

            // 返回销量统计数据
            Map<String, Object> salesStats = new HashMap<>();
            salesStats.put("todaySales", todaySales);
            salesStats.put("weekSales", weekSales);
            salesStats.put("monthSales", monthSales);
            salesStats.put("totalSales", totalSales);
            
            return salesStats;
        }
    }

    /**
     * 获取店铺营业额统计
     * @param shopId 店铺ID
     * @return 包含不同时间维度营业额数据的Map
     */
    public Map<String, Object> getRevenueStatistics(int shopId) throws Exception {
        try (Connection conn = JDBCUtils.getConnection()) {
            // 获取店铺基本信息
            Shop shop = shopDao.findById(shopId);
            if (shop == null) {
                throw new IllegalArgumentException("店铺不存在");
            }

            // 获取今日营业额
            LocalDateTime startOfDay = LocalDate.now().atStartOfDay();
            LocalDateTime endOfDay = LocalDate.now().plusDays(1).atStartOfDay();
            BigDecimal todayRevenue = orderDao.sumCompletedOrdersAmount(conn, shopId, startOfDay, endOfDay);
            
            // 获取本周营业额
            LocalDateTime startOfWeek = LocalDate.now().minusDays(LocalDate.now().getDayOfWeek().getValue() - 1).atStartOfDay();
            LocalDateTime endOfWeek = startOfWeek.plusDays(7);
            BigDecimal weekRevenue = orderDao.sumCompletedOrdersAmount(conn, shopId, startOfWeek, endOfWeek);
            
            // 获取本月营业额
            LocalDateTime startOfMonth = LocalDate.now().withDayOfMonth(1).atStartOfDay();
            LocalDateTime endOfMonth = startOfMonth.plusMonths(1);
            BigDecimal monthRevenue = orderDao.sumCompletedOrdersAmount(conn, shopId, startOfMonth, endOfMonth);
            
            // 获取总营业额
            BigDecimal totalRevenue = shop.getRevenue();

            // 返回营业额统计数据
            Map<String, Object> revenueStats = new HashMap<>();
            revenueStats.put("todayRevenue", todayRevenue);
            revenueStats.put("weekRevenue", weekRevenue);
            revenueStats.put("monthRevenue", monthRevenue);
            revenueStats.put("totalRevenue", totalRevenue);
            
            return revenueStats;
        }
    }

    public boolean toggleShopStatus(Integer shopId, String status) {
        Connection conn = null;
        try {
            conn = getConnection();
            Shop shop = shopDao.findById(shopId);
            if (shop == null) {
                return false;
            }
            shop.setStatus(status);
            return shopDao.update(conn, shop);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public boolean isShopBannedOrClosed(Integer shopId) {
        Connection conn = null;
        try {
            conn = getConnection();
            Shop shop = shopDao.findById(shopId);
            if (shop == null) {
                return false;
            }
            String status = shop.getStatus();
            return "banned".equals(status) || "closed".equals(status);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public List<Shop> getVisibleShopsForCustomers() {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.findAllVisibleShops(conn);
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public boolean banShop(Integer shopId) {
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            conn.setAutoCommit(false);
            
            // 1. 更新商家状态为banned
            Shop shop = shopDao.findById(shopId);
            if (shop == null) {
                throw new IllegalArgumentException("Shop not found");
            }
            shop.setStatus("banned");
            boolean updateSuccess = shopDao.update(conn, shop);
            
            if (!updateSuccess) {
                conn.rollback();
                return false;
            }
            
            // 2. 处理已确认订单的退款
            orderService.refundOrdersForBannedShop(shopId);
            
            conn.commit();
            return true;
        } catch (Exception e) {
            try {
                if (conn != null) {
                    conn.rollback();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (conn != null) {
                    conn.setAutoCommit(true);
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
